package com.atguigu.gmallrealtime.app.dwd.db;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmallrealtime.app.func.DwdBroadcastFunction;
import com.atguigu.gmallrealtime.bean.TableProcess;
import com.atguigu.gmallrealtime.common.Constant;
import com.atguigu.gmallrealtime.util.MyKafkaUtil;
import com.atguigu.gmallrealtime.util.MysqlUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchemaBuilder;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.sink.TopicSelector;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * @author yhm
 * @create 2023-10-07 10:21
 */
public class BaseDbApp {
    public static void main(String[] args) throws Exception {
        // TODO 1 创建flink环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        // TODO 2 添加检查点和状态后端
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//
//        //2.2 设置检查点超时时间
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        //2.3 设置job取消之后 检查点是否保留
//        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
//        //2.4 设置两个检查点之间最小的时间间隔
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
//        //2.5 设置重启策略
//        // env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30), Time.seconds(3)));
//
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//
//        System.setProperty("HADOOP_USER_NAME","atguigu");

        // TODO 3 读取ods层原始数据
        String groupId = "base_db_app_group";
        DataStreamSource<String> topicDbSource = env.fromSource(MyKafkaUtil.getKafkaSource(Constant.TOPIC_ODS_DB, groupId), WatermarkStrategy.noWatermarks(), "topic_db_source");

        // TODO 4 进行清洗过滤
        // 过滤加转换
        SingleOutputStreamOperator<JSONObject> mainStream = topicDbSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    // 实时数仓不处理事实表的历史数据
                    String type = jsonObject.getString("type");
                    if ("insert".equals(type) || "update".equals(type) || "delete".equals(type)) {
                        out.collect(jsonObject);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        // TODO 5 flinkCDC读取配置表数据
        DataStreamSource<String> dataStreamSource = env.fromSource(MysqlUtil.getMySqlSource("gmall_config", "gmall_config.table_process"), WatermarkStrategy.noWatermarks(), "table_process").setParallelism(1);

        // TODO 6 过滤清洗dwd相关数据
        SingleOutputStreamOperator<JSONObject> tableProcessStream = dataStreamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        // TODO 7 广播配置表数据
        MapStateDescriptor<String, TableProcess> mapStateDescriptor = new MapStateDescriptor<String, TableProcess>("table_process_state",String.class,TableProcess.class);
        BroadcastStream<JSONObject> broadcastStream = tableProcessStream.broadcast(mapStateDescriptor);

        // TODO 8 连接主流和配置流
        BroadcastConnectedStream<JSONObject, JSONObject> connectStream = mainStream.connect(broadcastStream);

        // TODO 9 根据配置流过滤出主流相关的事实表
        SingleOutputStreamOperator<JSONObject> processStream = connectStream.process(new DwdBroadcastFunction(mapStateDescriptor));

//        processStream.print("main>>>");

        // TODO 10 将数据写出到kafka
        processStream.sinkTo(MyKafkaUtil.getKafkaSinkWithTopicName( new KafkaRecordSerializationSchemaBuilder<JSONObject>()
                .setTopicSelector(new TopicSelector<JSONObject>() {
                    @Override
                    public String apply(JSONObject jsonObject) {
                        return jsonObject.getString("sink_table");
                    }
                })
                .setValueSerializationSchema(new SerializationSchema<JSONObject>() {
                    @Override
                    public byte[] serialize(JSONObject element) {
                        element.remove("sink_table");
                        return Bytes.toBytes(element.toJSONString());
                    }
                })
                .build()));

//        processStream.map(new MapFunction<JSONObject, String>() {
//            @Override
//            public String map(JSONObject value) throws Exception {
//                return value.toJSONString();
//            }
//        }).sinkTo(MyKafkaUtil.getKafkaSinkWithTopicName(new KafkaRecordSerializationSchemaBuilder<String>()
//                .setTopicSelector(new TopicSelector<String>() {
//                    @Override
//                    public String apply(String s) {
//                        JSONObject jsonObject = JSON.parseObject(s);
//                        return jsonObject.getString("sink_table");
//                    }
//                })
//                .setValueSerializationSchema(new SimpleStringSchema())
//                .build()));



        // TODO 11 执行环境
        env.execute();
    }
}
